﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Inspired.Euler
{
    /// <summary>
    /// If p is the perimeter of a right angle triangle with integral length sides, {a,b,c},
    /// there are exactly three solutions for p = 120.
    /// 
    /// {20,48,52}, {24,45,51}, {30,40,50}
    /// 
    /// For which value of p <= 1000, is the number of solutions maximised?
    /// </summary>
    public static class Problem039
    {
        /// <summary>
        /// If p is the perimeter of a right angle triangle, {a, b, c}, which value, for p <= 1000, has the most solutions?
        /// </summary>
        [EulerProblem(39, Title = "If p is the perimeter of a right angle triangle, {a, b, c}, which value, for p <= 1000, has the most solutions?")]
        public static long Solve()
        {
            //return 120L
            //    .GetTriangles()
            //    //.Display()
            //    .Count();

            // http://www.thattommyhall.com/2008/04/12/project-euler-39/

            return
                Enumerable.Range(3, 999)
                .Select(perimeter => new
                    {
                        Perimeter = perimeter,
                        Solutions = ((long)perimeter).GetSolutions()
                    })
                .OrderByDescending(right => right.Solutions.Count())
                .First()
                .Perimeter;
        }

        static IEnumerable<int[]> GetSolutions(this long p)
        {
            for (int a = 1; a < p / 3; a++)
            {
                for (int b = a; b < (p - a) / 2; b++)
                {
                    int c = (int)p - a - b;
                    if (a * a + b * b == c * c)
                    {
                        yield return new []{ a, b, c };
                    }
                }
            }
        }
    }
}
